<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/28
 * Time: 15:20
 * @link http://www.lmterp.cn
 */
namespace app\command;

use app\common\model\ChannelExpress;
use app\common\model\ChannelOrders;
use app\common\model\OrdersReturn;
use app\common\model\PurchaseTrack;
use app\common\model\WarehouseAllot;
use think\console\input\Option;
use think\facade\Log;

/**
 * 同步物流信息
 * Class Logistics
 * @package app\command
 */
class Logistics extends BaseCommand
{
    /**
     * 默认同步三个月内订单
     * @var int
     */
    protected $month = 3;

    protected $ids;

    protected function configure()
    {
        $this->setName('logistics')
             ->addOption("type", null, Option::VALUE_REQUIRED, "同步的订单类型，默认全部，可选【channel, return, purchase, allot】")
             ->addOption("month", null, Option::VALUE_REQUIRED, "同步多少个月内的物流信息")
             ->addOption("ids", null, Option::VALUE_REQUIRED, "指定订单id，多个使用逗号分隔");
    }

    protected function handler()
    {
        if($this->input->hasOption("month"))
        {
            $this->month = intval($this->input->getOption("month"));
            if($this->month > 3 || $this->month < 1) $this->month = 3;
        }
        if($this->input->hasOption('ids'))
        {
            $ids = $this->input->getOption('ids');
            $this->ids = explode(',', replaceStr($ids));
        }
        $action = $this->input->hasOption('type')
            ? $this->input->getOption('type')
            : ['channel', 'return', 'purchase', 'allot'];
        if(!is_array($action)) $action = [$action];
        Log::info("开始获取物流信息");
        foreach($action as $type)
        {
            $fn = 'sync' . ucfirst($type) . 'Order';
            if(method_exists($this, $fn)) $this->$fn();
        }
        Log::info("完成获取物流信息");
    }

    /**
     * 同步发货订单物流信息
     * @date 2021/03/05
     * @author longli
     */
    protected function syncChannelOrder()
    {
        $where = [];
        if(!empty($this->ids))
        {
            $where[] = ['ch_id', 'in', $this->ids];
        }
        else
        {
            $where = [
                ['track_num', 'neq', ''],
                ['is_cancel', 'eq', ChannelOrders::IS_NO],
                ['create_time', 'gt', date('Y-m-d', strtotime("-{$this->month}month"))],
                ['track_status', 'not in', [
                    ChannelOrders::TRACK_STATUS_WAIT,
                    ChannelOrders::TRACK_STATUS_TIMEOUT,
                    ChannelOrders::TRACK_STATUS_RECV,
                    // ChannelOrders::TRACK_STATUS_EXCEPTION,
                    ]
                ],
            ];
        }
        ChannelOrders::field(['ch_id'])->where($where)->chunk(40, function($result)
        {
            $ids = [];
            foreach($result as $ch) $ids[] = $ch->ch_id;
            $track = new \app\common\service\logistics\Track51($ids);
            $track->channelOrder();
            $error = $track->getError();
            if(!empty($error)) Log::info(join(', ', $error));
        });
    }

    /**
     * 同步退货订单物流信息
     * @date 2021/03/05
     * @author longli
     */
    protected function syncReturnOrder()
    {
        $where = [];
        if(!empty($this->ids))
        {
            $where[] = ['rid', 'in', $this->ids];
        }
        else
        {
            $where = [
                ['track_num', 'neq', ''],
                ['create_time', 'gt', date('Y-m-d', strtotime("-{$this->month}month"))],
                ['track_status', 'not in', [
                    ChannelOrders::TRACK_STATUS_TIMEOUT,
                    ChannelOrders::TRACK_STATUS_RECV,
                    ChannelOrders::TRACK_STATUS_EXCEPTION,
                    ]
                ],
            ];
        }
        OrdersReturn::field(['rid'])->where($where)->chunk(40, function($result)
        {
            $ids = [];
            foreach($result as $order) $ids[] = $order->rid;
            $track = new \app\common\service\logistics\Track51($ids);
            $track->returnOrder();
            $error = $track->getError();
            if(!empty($error)) Log::info(join(', ', $error));
        });
    }

    /**
     * 同步采购单物流信息
     * @date 2021/03/05
     * @author longli
     */
    protected function syncPurchaseOrder()
    {
        $where = [
            ['track_num', 'neq', ''],
            //['is_recv', 'eq', PurchaseTrack::IS_NO],
            ['track_status', 'not in', [ChannelExpress::TRACK_STATUS_SIGN_RECV]]
        ];
        if(!empty($this->ids))
        {
            $where[] = ['track_id', 'in', $this->ids];
        }
        else
        {
            $where[] = ['create_time', 'egt', date('Y-m-d', strtotime("-{$this->month}month"))];
        }

        PurchaseTrack::field(['track_id'])->where($where)->chunk(1000, function($tracks)
        {
            $ids = [];
            foreach($tracks as $track) $ids[] = $track->track_id;
            $kuaidi100 = new \app\common\service\logistics\Kuaidi100($ids);
            $kuaidi100->purchase();
            $error = $kuaidi100->getError();
            if(!empty($error)) Log::info(join(', ', $error));
        });
    }

    /**
     * 同步调拨单物流信息
     * @date 2021/03/18
     * @author longli
     */
    protected function syncAllotOrder()
    {
        $where = [
            ['track_num', 'neq', ''],
            ['track_status', 'not in', [ChannelExpress::TRACK_STATUS_SIGN_RECV]]
        ];
        if(!empty($this->ids))
        {
            $where[] = ['allot_id', 'in', $this->ids];
        }
        else
        {
            $where[] = ['create_time', 'egt', date('Y-m-d', strtotime("-{$this->month}month"))];
        }
        WarehouseAllot::field(['allot_id'])->where($where)->chunk(1000, function($allots)
        {
            $ids = [];
            foreach($allots as $allot) $ids[] = $allot->allot_id;
            $kuaidi100 = new \app\common\service\logistics\Kuaidi100($ids);
            $kuaidi100->allot();
            $error = $kuaidi100->getError();
            if(!empty($error)) Log::info(join(', ', $error));
        });
    }
}
